package kite.sso.config;

import com.alibaba.druid.pool.DruidDataSource;
import kite.sso.service.comp.KiteLoginAuthProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 功能描述: <br>
 * 所属包名: kite.sso.config<br>
 * 创建人　: 白剑<br>
 * 创建时间: 2018/06/04 23:22:24<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DruidDataSource dataSource;

    @Autowired
    private KiteLoginAuthProvider authProvider;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .requestMatchers()
                .antMatchers("/login", "/", "/oauth/authorize")
                .and()
            .requestMatchers()
                .antMatchers("/sys/**")
                .and()
            .requestMatchers()
                .antMatchers("/tran/**")
                .and()
            .requestMatchers()
                .antMatchers("/webjars/**", "/js/**", "/css/**", "/images/**")
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
            .anonymous()
                .and()
            .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
            .csrf().disable(); // 关闭跨域攻击tocken
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
        auth.jdbcAuthentication().dataSource(dataSource)
            .passwordEncoder(new BCryptPasswordEncoder(KiteSsoConfig.PASSWORD_STRENGTH));
    }

}
